package components.bullets
{
	import actor.Tower;
	
	import capricornus.actor.Actor;
	import capricornus.core.RefreshManager;
	import capricornus.events.RefreshEvent;
	
	import config.DemonConfig;
	
	import flash.utils.Dictionary;
	
	import scene.Scene;

	public class BulletManager
	{
		public static const instance:BulletManager = new BulletManager();
		
		private var _dict:Dictionary;
		
		private var _isAddListener:Boolean = false;
		
		public function BulletManager()
		{
			init();
		}
		
		private function init():void
		{
			_dict = new Dictionary();
			start();
		}
		
		public function start():void
		{
			if( !_isAddListener )
			{
				_isAddListener = true;
				RefreshManager.instance.addEventListener( RefreshEvent.REFRESH, onRefresh, false, 0, true );
			}
		}
		
		public function stop():void
		{
			if( _isAddListener )
			{
				_isAddListener = false;
				RefreshManager.instance.removeEventListener( RefreshEvent.REFRESH, onRefresh );
			}
		}
		
		public function shoot( vo:BulletVO ):void
		{
			var xml:XML = DemonConfig.instance.getBulletDataByID( vo.bulletID );
			if( xml==null ) return;
			
			vo.speed = int(xml.@speed)/1000;
			vo.type = int(xml.@type);
			vo.isAreaHit = int(xml.@areaHit)==1;
			vo.areaHitRange = int(xml.@areaHitRange);
			
			var bullet:Bullet = new Bullet( vo );
			bullet.setLocation( vo.tower.x, vo.tower.y );
			bullet.activate();
			Scene.instance.addBullet( bullet );
		}
		
		internal function addBullet( bullet:Bullet ):void
		{
			_dict[bullet] = bullet;
		}
		
		internal function removeBullet( bullet:Bullet ):void
		{
			if( _dict[bullet] != null )
			{
				delete _dict[bullet];
			}
		}
		
		private function onRefresh( e:RefreshEvent ):void
		{
			for( var i:* in _dict )
			{
				var bullet:Bullet = _dict[i];
				bullet.refresh( e.data );
			}
		}
	}
}












